package com.zhu.servlet;

import com.zhu.dao.ClassDao;
import com.zhu.dao.StudentDao;
import com.zhu.pojo.Classes;
import com.zhu.pojo.Student;
import com.zhu.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
@WebServlet("/updateStudent.do")
public class UpdateStuServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int sid = Integer.parseInt(req.getParameter("sid"));
        Student student = null;
        String sname = req.getParameter("sname");
        List<Classes> classesList=null;
        try {
            classesList = new ClassDao().getClasses();
            student = new StudentService().getStudentById(sid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        req.setAttribute("classesList",classesList);
        req.setAttribute("student",student);
        req.getRequestDispatcher("/WEB-INF/jsp/updateStudent.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int hid=0;
        String[] hobbies = req.getParameterValues("hobby");
        for (String hobby : hobbies) {
            hid += Integer.parseInt(hobby);
        }
        String sname = req.getParameter("sname");
        int cid = Integer.parseInt(req.getParameter("cid"));
        int sid = Integer.parseInt(req.getParameter("sid"));
        Student student = new Student();
        student.setSname(sname);
        student.setCid(cid);
        student.setSid(sid);
        student.setHid(hid);
        new StudentDao().updateStudent(student);
        resp.sendRedirect("index.do");
    }
}
